<?php

namespace app\api\service;

use think\facade\Db;

class GoodsItemService
{

    /**
     *
     * 购物车订单
     * param int|array
     *
     * */
    public static function findSkuGoods($data)
    {
        $count = count($data);

        if ($count<1){
            return [];
        }
        $query =  Db::name('goods_item')
            ->field('a.goods_id,b.goods_name,b.main_image,a.attr,a.image,a.market_price,a.sell_price,a.stock')
            ->alias('a')
            ->join('goods b','a.goods_id=b.id')
            ->where(['b.status' => 1]);

        if ($count >1){
            $ids = array_column($data,'sku_id');
            $buy_nums = array_column($data,'buy_num');
            $goods = $query->select($ids);
        }

        if ($count ==1){
            $ids = array_column($data,'sku_id');
            $buy_nums = array_column($data,'buy_num');
            $goods = $query->where('a.id',$ids[0])->limit(1)->select();
        }

        if ($goods->isEmpty()){
            return [];
        }

        $arr = [];
        $real_amount = 0;
        foreach ($goods as $k => $v){
            $v['buy_num'] = $buy_nums[$k];
            $v['image'] = !empty($v['image']) ? $v['image'] : $v['main_image'];
            $v['total_amount'] = $v['sell_price']*$buy_nums[$k];
            $real_amount += $v['total_amount'];
            $arr[$k] = $v;
        }

        return empty($arr) ? [] : ['orderItem' => $arr,'real_amount' => $real_amount];

    }
}